package store.lunangangster.engine.impl.config;

import java.io.InputStream;
import java.net.URL;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import store.lunangangster.engine.ProcessEngineConfiguration;

public class SpringBeanDefinitionResolver {

  public static ProcessEngineConfiguration resolveProcessEngineConfiguration(InputStream is, String beanName) {
    Resource resource = new InputStreamResource(is);
    return resolveProcessEngineConfiguration(resource, beanName);
  }

  public static ProcessEngineConfiguration resolveProcessEngineConfiguration(String resourcePath, String beanName) {
    Resource resource = new ClassPathResource(resourcePath);
    return resolveProcessEngineConfiguration(resource, beanName);
  }

  public static ProcessEngineConfiguration resolveProcessEngineConfiguration(Resource resource, String beanName) {
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
    xmlBeanDefinitionReader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
    // 加载BeanDefinition到beanFactory中
    xmlBeanDefinitionReader.loadBeanDefinitions(resource);
    ProcessEngineConfiguration processEngineConfiguration = beanFactory.getBean(beanName,
        ProcessEngineConfiguration.class);
    String urlString;
    try {
      URL url = resource.getURL();
      urlString = url.toString();
    } catch (Exception e) {
      // ignore Exception
      urlString = resource.getDescription();
    }
    processEngineConfiguration.setPath(urlString);
    processEngineConfiguration.setName(beanName);

    return processEngineConfiguration;
  }

}
